const { request } = require('../../utils/request');
const { debounce } = require('../../utils/common');
const pageBehavior = require('../../utils/pageBehavior');

const DEFAULT_LIMIT = 20;

Page({
  behaviors: [pageBehavior],

  data: {
    keyword: '',
    faqs: [],
    expandedIds: [],
    limit: DEFAULT_LIMIT
  },

  onLoad() {
    this.fetchFaqs('');
  },

  onKeywordInput(event) {
    const value = event.detail?.value || '';
    this.setData({ keyword: value });
    this.debouncedFetch(value);
  },

  onSearch() {
    this.fetchFaqs(this.data.keyword);
  },

  onClear() {
    this.setData({ keyword: '' });
    this.fetchFaqs('');
  },

  // 使用防抖函数
  debouncedFetch: debounce(function(value) {
    this.fetchFaqs(value);
  }, 300),

  async fetchFaqs(rawKeyword) {
    const keyword = (rawKeyword || '').trim();
    const params = [`limit=${this.data.limit}`];
    if (keyword) {
      params.push(`keyword=${encodeURIComponent(keyword)}`);
    }
    const url = `/api/miniapp/faqs?${params.join('&')}`;

    await this.executeAsync(
      async () => {
        const res = await request({ url, method: 'GET', showErrorToast: false });
        const list = this.extractList(res?.data);
        const normalized = list.map((item) => {
          const tags = this.extractTags(item.tags);
          const expanded = this.data.expandedIds.includes(item.id);
          return {
            id: item.id,
            question: item.question || item.title || '未命名问题',
            answer: item.answer || item.content || '',
            tags,
            tagsDisplay: tags.length ? tags.join(' · ') : '常见问题',
            expanded
          };
        });
        
        if (normalized.length === 0) {
          this.setEmpty(true, keyword ? '未找到相关问题' : '暂无数据');
        } else {
          this.setEmpty(false);
          this.setData({ faqs: normalized });
        }
      },
      {
        showLoading: true,
        showError: true,
        defaultMessage: '加载失败，请稍后重试'
      }
    );
  },

  extractList(raw) {
    if (Array.isArray(raw)) {
      return raw;
    }
    if (Array.isArray(raw?.records)) {
      return raw.records;
    }
    if (Array.isArray(raw?.list)) {
      return raw.list;
    }
    if (Array.isArray(raw?.data)) {
      return raw.data;
    }
    return [];
  },

  extractTags(tagValue) {
    if (!tagValue) {
      return [];
    }
    if (Array.isArray(tagValue)) {
      return tagValue;
    }
    return tagValue
      .split(',')
      .map((tag) => tag.trim())
      .filter((tag) => tag);
  },

  toggleExpand(event) {
    const id = event.currentTarget.dataset.id;
    if (!id) {
      return;
    }
    const expandedIds = [];
    const updated = this.data.faqs.map((item) => {
      if (item.id === id) {
        const expanded = !item.expanded;
        if (expanded) {
          expandedIds.push(item.id);
        }
        return Object.assign({}, item, { expanded });
      }
      if (item.expanded) {
        expandedIds.push(item.id);
      }
      return item;
    });
    this.setData({ faqs: updated, expandedIds });
  },

  reload() {
    this.clearError();
    this.fetchFaqs(this.data.keyword);
  }
});
